<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\Config
 *
 * @property int $id 自增主键
 * @property string $title 配置名
 * @property string $value 配置值
 * @property string $desc 配置描述
 * @property \Illuminate\Support\Carbon|null $created_at 添加时间
 * @property \Illuminate\Support\Carbon|null $updated_at 更新时间
 * @method static \Illuminate\Database\Eloquent\Builder|Config newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Config newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Config query()
 * @method static \Illuminate\Database\Eloquent\Builder|Config whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Config whereDesc($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Config whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Config whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Config whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Config whereValue($value)
 * @mixin \Eloquent
 */
class Config extends Model
{
    use HasDateTimeFormatter;

    protected $table = 'config';

    public function getConfig($title)
    {
        $value = self::where('title', $title)
            ->firstOr(function () {
                return '';
            });
        return $value->value ?? $value;
    }

    public function createOrUpdate($title = '', $value = '')
    {
        if ($title) {
            $config = self::where('title', $title)
                ->first();
            if ($config) {
                if ($config->value !== $value) {
                    self::where('title', $title)
                        ->update([
                            'value' => $value,
                            'updated_at' => date('Y-m-d H:i:s'),
                        ]);
                }
            } else {
                self::where('title', $title)
                    ->insert([
                        'title' => $title,
                        'value' => $value,
                        'created_at' => date('Y-m-d H:i:s'),
                    ]);
            }
        }
    }

}
